package com.web.Controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

import com.jfinal.core.Controller;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;


public class LoginController extends Controller{
	private static Logger logger = Logger.getLogger(LoginController.class);
	public void index() {
		
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
		logger.info("登录日期"+df.format(new Date().getTime()));
		setAttr("msg","start");
    	render("/login/index.html");
	}
	public void dologin() {
		 PropKit.use("jfinal.properties"); 
		 String username = getPara("username","");
		 String password = getPara("password","");
		 String rememberMeStr = getPara("rememberMe","");
		 boolean rememberMe=false;
		 if (rememberMeStr.equals("on")) {
			 rememberMe=true;
		 }
		    try {
		    	String salt=PropKit.get("salt");
				password= new Md5Hash(password, salt).toString();
				logger.info(password);
		        Subject currentUser = SecurityUtils.getSubject();
		        Session session = currentUser.getSession();
		        UsernamePasswordToken token = new UsernamePasswordToken(username, password,rememberMe);
				currentUser.login(token);
				
				String SQL = "SELECT * FROM users WHERE username =? ";
				Record userinfo = Db.findFirst(SQL, username);
				session.setAttribute("userinfo",userinfo);
				logger.info("当前用户id="+userinfo.getInt("id").toString());
				if(currentUser.hasRole("admin")){
					logger.info("roledes"+"管理员");
					redirect("/adminmg/");
				}else{
					logger.info("roledes"+"普通用户");
					redirect("/adminmg/");
				}

		    } catch (Exception e) {
		    	logger.info("err"+e.toString());
		    	setAttr("msg","用户名或密码错误");
		    	render("/login/index.html");
		       
		    }
		
	}
}
